import React, { useState, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { Table, Pagination, TimePicker } from 'antd';
import dayjs from 'dayjs';
import './index.css';
import { useNavigate } from 'react-router-dom';

function Main() {
    // 状态管理：当前日期和时间
    const [currentDate, setCurrentDate] = useState('');
    const [currentTime, setCurrentTime] = useState('');
    // 分页状态管理
    const [appointmentPage, setAppointmentPage] = useState(1);
    const pageSize = 3; // 每页显示条数
    // ECharts 实例引用
    const chartRef = useRef(null);
    const businessChart = useRef(null);

    // 修改预约时间弹窗状态
    const [editingAppointment, setEditingAppointment] = useState(null);
    const [newTime, setNewTime] = useState(null); // 使用dayjs对象
    const [showEditModal, setShowEditModal] = useState(false);

    // 新增客户弹窗状态
    const [showAddCustomerModal, setShowAddCustomerModal] = useState(false);
    const [newCustomer, setNewCustomer] = useState({
        name: '',
        phone: '',
        gender: 'male'
    });

    // 预约数据状态
    const [appointmentData, setAppointmentData] = useState([
        {
            id: 1,
            time: '09:30 - 10:30',
            customer: '李明',
            phone: '13800138000',
            customerId: 'C2023056',
            avatar: 'https://picsum.photos/id/91/40/40',
            service: '推拿按摩（60分钟）',
            payment: '¥268'
        },
        {
            id: 2,
            time: '11:00 - 12:00',
            customer: '张华',
            phone: '13900139000',
            customerId: 'C2023042',
            avatar: 'https://picsum.photos/id/92/40/40',
            service: '针灸治疗（60分钟）',
            payment: ''
        },
        {
            id: 3,
            time: '14:00 - 15:00',
            customer: '赵丽',
            phone: '13700137000',
            customerId: 'C2023078',
            avatar: 'https://picsum.photos/id/93/40/40',
            service: '艾灸调理（60分钟）',
            payment: '',
            note: '客户有颈椎病史'
        },
        {
            id: 4,
            time: '15:30 - 16:30',
            customer: '陈杰',
            phone: '13600136000',
            customerId: 'C2023015',
            avatar: 'https://picsum.photos/id/94/40/40',
            service: '拔罐疗法（45分钟）',
            payment: ''
        },
        {
            id: 5,
            time: '16:45 - 17:45',
            customer: '王芳',
            phone: '13500135000',
            customerId: 'C2023091',
            avatar: 'https://picsum.photos/id/96/40/40',
            service: '推拿按摩（60分钟）',
            payment: ''
        },
        {
            id: 6,
            time: '18:00 - 19:00',
            customer: '刘强',
            phone: '13400134000',
            customerId: 'C2023027',
            avatar: 'https://picsum.photos/id/97/40/40',
            service: '针灸+艾灸组合（60分钟）',
            payment: ''
        }
    ]);

    // 确认弹窗状态
    const [alertModal, setAlertModal] = useState({
        visible: false,
        title: '',
        content: '',
        confirmText: '确认',
        cancelText: '取消',
        onConfirm: null,
        onCancel: null,
        showCancel: true
    });

    const navigate = useNavigate();
    function cure_order() {
        navigate('/cure');
    }

    function statistics_data() {
        navigate('/statistics');
    }

    function cure_ripe() {
        navigate('/ripe');
    }

    // 保存新的预约时间
    const saveNewTime = () => {
        if (!newTime) return;

        // 计算结束时间（假设时长不变）
        const duration = editingAppointment.time.split(' - ')[1]
            .split(':').reduce((acc, time) => acc * 60 + parseInt(time), 0) -
            editingAppointment.time.split(' - ')[0]
                .split(':').reduce((acc, time) => acc * 60 + parseInt(time), 0);

        const hours = newTime.hour();
        const minutes = newTime.minute();
        const endHours = Math.floor((hours * 60 + minutes + duration) / 60);
        const endMinutes = (hours * 60 + minutes + duration) % 60;
        const formattedEndTime = `${endHours.toString().padStart(2, '0')}:${endMinutes.toString().padStart(2, '0')}`;

        const updatedTime = `${newTime.format('HH:mm')} - ${formattedEndTime}`;

        // 更新预约数据
        setAppointmentData(appointmentData.map(item =>
            item.id === editingAppointment.id
                ? { ...item, time: updatedTime }
                : item
        ));

        // 关闭弹窗
        setShowEditModal(false);
        setEditingAppointment(null);
        setNewTime(null);
    };

    // 保存新客户信息
    const saveNewCustomer = () => {
        if (!newCustomer.name || !newCustomer.phone) return;

        // 这里可以添加保存到服务器的逻辑
        console.log('新客户信息:', newCustomer);

        // 显示成功消息
        showAlert({
            title: '登记成功',
            content: `客户 <strong>${newCustomer.name}</strong> 已成功登记！`,
            confirmText: '确定',
            showCancel: false,
            onConfirm: () => {
                setNewCustomer({ name: '', phone: '', gender: 'male' });
                setShowAddCustomerModal(false);
            }
        });
    };

    // 打开修改时间弹窗
    const handleEditTime = (record) => {
        setEditingAppointment(record);
        // 提取开始时间作为默认值并转换为dayjs对象
        const startTimeStr = record.time.split(' - ')[0];
        const [hours, minutes] = startTimeStr.split(':').map(Number);
        const defaultTime = dayjs().hour(hours).minute(minutes);
        setNewTime(defaultTime);
        setShowEditModal(true);
    };

    // 显示确认弹窗
    const showAlert = (options) => {
        setAlertModal({
            visible: true,
            title: options.title || '提示',
            content: options.content || '',
            confirmText: options.confirmText || '确认',
            cancelText: options.cancelText || '取消',
            onConfirm: options.onConfirm || null,
            onCancel: options.onCancel || null,
            showCancel: options.showCancel !== false
        });
    };

    // 关闭确认弹窗
    const closeAlert = () => {
        setAlertModal({ ...alertModal, visible: false });
    };

    // 点击确认按钮
    const handleConfirm = () => {
        if (alertModal.onConfirm && typeof alertModal.onConfirm === 'function') {
            alertModal.onConfirm();
        }
        closeAlert();
    };

    // 点击取消按钮
    const handleCancel = () => {
        if (alertModal.onCancel && typeof alertModal.onCancel === 'function') {
            alertModal.onCancel();
        }
        closeAlert();
    };

    // 初始化日期和时间
    useEffect(() => {
        // 更新日期
        const updateDate = () => {
            const now = new Date();
            const options = {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            };
            setCurrentDate(now.toLocaleDateString('zh-CN', options));
        };

        // 更新时间
        const updateTime = () => {
            const now = new Date();
            const options = {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            };
            setCurrentTime(now.toLocaleTimeString('zh-CN', options));
        };

        // 初始化执行
        updateDate();
        updateTime();

        // 定时器：每秒更新时间，每天更新日期
        const timeInterval = setInterval(updateTime, 1000);
        const dateInterval = setInterval(updateDate, 86400000);

        // 清理定时器
        return () => {
            clearInterval(timeInterval);
            clearInterval(dateInterval);
        };
    }, []);

    // 初始化 ECharts 图表
    useEffect(() => {
        if (chartRef.current) {
            // 初始化图表实例
            businessChart.current = echarts.init(chartRef.current);

            // 图表配置项
            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    bottom: '0%',
                    left: 'center',
                    textStyle: {
                        fontSize: 11
                    },
                    itemWidth: 12,
                    itemHeight: 12,
                    padding: 15
                },
                series: [
                    {
                        name: '收入占比',
                        type: 'pie',
                        radius: ['50%', '80%'],
                        center: ['50%', '40%'], // 将饼图位置往上调整
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 4,
                            borderColor: '#fff',
                            borderWidth: 0
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 14,
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            { value: 35, name: '推拿', itemStyle: { color: '#704214' } },
                            { value: 25, name: '针灸', itemStyle: { color: '#556B2F' } },
                            { value: 20, name: '艾灸', itemStyle: { color: '#D2B48C' } },
                            { value: 10, name: '拔罐', itemStyle: { color: '#8B5A2B' } },
                            { value: 10, name: '其他', itemStyle: { color: '#A67C52' } }
                        ]
                    }
                ]
            };

            // 设置图表配置项
            businessChart.current.setOption(option);

            // 窗口大小变化时 resize 图表
            const handleResize = () => {
                businessChart.current?.resize();
            };

            window.addEventListener('resize', handleResize);

            // 清理函数
            return () => {
                window.removeEventListener('resize', handleResize);
                businessChart.current?.dispose();
            };
        }
    }, []);


    // 监听窗口大小变化，重置轮播位置
    useEffect(() => {
        const handleResize = () => {
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    // 房间数据 - 包含状态标识和占用数量
    const roomData = [
        {
            id: 1,
            name: '一号房间',
            status: 'occupied', // occupied=已满, free=空闲, reserved=未满, disabled=停用
            occupiedCount: 3 // 已占用位置数，每个房间固定3个位置
        },
        {
            id: 2,
            name: '二号房间',
            status: 'free',
            occupiedCount: 0
        },
        {
            id: 3,
            name: '三号房间',
            status: 'reserved',
            occupiedCount: 1
        },
        {
            id: 4,
            name: '四号房间',
            status: 'reserved',
            occupiedCount: 2
        },
        {
            id: 5,
            name: '五号房间',
            status: 'disabled',
            occupiedCount: 0
        }
    ];

    // 状态文本映射
    const statusTextMap = {
        occupied: '已满',
        free: '空闲',
        reserved: '未满',
        disabled: '停用'
    };

    // 状态图标映射
    const statusIconMap = {
        occupied: 'fa-exclamation-circle',
        free: 'fa-check-circle',
        reserved: 'fa-clock-o',
        disabled: 'fa-ban'
    };

    // 处理预约列表分页
    const filteredAppointments = appointmentData.slice(
        (appointmentPage - 1) * pageSize,
        appointmentPage * pageSize
    );
    const appointmentTotal = appointmentData.length;

    // 预约列表列配置
    const appointmentColumns = [
        {
            title: '时间',
            dataIndex: 'time',
            key: 'time',
            width: 140,
            render: (time) => (
                <div className="appointment-time-status">
                    <span className="time" style={{ fontSize: '1rem' }}>{time}</span>
                </div>
            )
        },
        {
            title: '用户姓名',
            dataIndex: 'customer',
            key: 'customer',
            width: 120,
            render: (customer) => <span style={{ fontSize: '1rem', fontWeight: 500 }}>{customer}</span>
        },
        {
            title: '电话号码',
            dataIndex: 'phone',
            key: 'phone',
            width: 150,
            render: (phone) => <span style={{ fontSize: '1rem' }}>{phone}</span>
        },
        {
            title: '项目',
            dataIndex: 'service',
            key: 'service',
            render: (service) => <span style={{ fontSize: '1rem' }}>{service}</span>
        },
        {
            title: '操作',
            key: 'action',
            width: 160,
            render: (_, record) => (
                <div className="appointment-actions">
                    <button
                        style={getButtonStyle('green')}
                        className="btn-icon"
                        onClick={(e) => {
                            e.stopPropagation();
                            showAlert({
                                title: '确认预约',
                                content: `确定要确认 <strong>${record.customer}</strong> 的预约吗？`,
                                confirmText: '确认',
                                cancelText: '取消',
                                onConfirm: () => {
                                    console.log(`确认预约 #${record.id}`);
                                    // 这里可以添加确认预约的业务逻辑
                                }
                            });
                        }}
                        title="确认预约"
                    >
                        <i className="fa fa-check"></i>
                    </button>
                    <button
                        style={getButtonStyle('red')}
                        className="btn-icon"
                        onClick={(e) => {
                            e.stopPropagation();
                            showAlert({
                                title: '取消预约',
                                content: `确定要取消 <strong>${record.customer}</strong> 的预约吗？`,
                                confirmText: '确认取消',
                                cancelText: '保留',
                                onConfirm: () => {
                                    console.log(`取消预约 #${record.id}`);
                                    // 这里可以添加取消预约的业务逻辑
                                }
                            });
                        }}
                        title="取消预约"
                    >
                        <i className="fa fa-times"></i>
                    </button>
                </div>
            )
        }
    ];

    // 获取按钮样式
    const getButtonStyle = (variant) => {
        switch (variant) {
            case 'primary':
                return {
                    backgroundColor: '#704214',
                    color: 'white',
                    border: 'none'
                };
            case 'secondary':
                return {
                    backgroundColor: '#556B2F',
                    color: 'white',
                    border: 'none'
                };
            case 'green':
                return {
                    backgroundColor: '#f0fdf4',
                    color: '#166534',
                    border: 'none'
                };
            case 'blue':
                return {
                    backgroundColor: '#eff6ff',
                    color: '#1e40af',
                    border: 'none'
                };
            case 'gray':
                return {
                    backgroundColor: '#f3f4f6',
                    color: '#4b5563',
                    border: 'none'
                };
            case 'red':
                return {
                    backgroundColor: '#fee2e2',
                    color: '#b91c1c',
                    border: 'none'
                };
            default:
                return {
                    backgroundColor: 'transparent',
                    color: '#704214',
                    border: '1px solid #704214'
                };
        }
    };

    return (
        <div className='main'>
            <div className="workbench-container">
                {/* 欢迎信息与日期区域 */}
                <section className="welcome-section">
                    <div className="welcome-content">
                        <div className="welcome-greeting">
                            <div className="icon-container">
                                <i className="fa fa-user-md icon-container_icon" ></i>
                            </div>
                            <div>
                                <h2>早上好，张前台</h2>
                                <p className='main_time'>
                                    <i className="fa fa-calendar-check-o"></i>
                                    今天是 <span className="current-date">{currentDate}</span>
                                </p>
                            </div>
                        </div>
                        <div className="current-time-container">
                            <div className="time-icon">
                                <i className="fa fa-clock-o"></i>
                            </div>
                            <span className="time-display">{currentTime}</span>
                        </div>
                    </div>
                </section>

                {/* 快速操作 */}
                <div className="quick-actions card quick-actions-top">
                    <div className="action-grid action-grid-top">
                        <button className="action-button secondary" onClick={cure_ripe}>
                            <i className="fa fa-calendar-plus-o"></i>
                            <span>新增预约</span>
                        </button>

                        <button
                            className="action-button primary"
                            onClick={() => setShowAddCustomerModal(true)}
                        >
                            <i className="fa fa-user-plus"></i>
                            <span>新客户登记</span>
                        </button>

                        <button className="action-button green" onClick={cure_order}>
                            <i className="fa fa-credit-card"></i>
                            <span>收银结算</span>
                        </button>

                        <button className="action-button blue" onClick={statistics_data}>
                            <i className="fa fa-refresh"></i>
                            <span>数据报表</span>
                        </button>
                    </div>
                </div>

                {/* 今日预约与房间卡片 */}
                <div className="appointment-and-actions">
                    {/* 今日预约 */}
                    <div className="appointment-list-container card">
                        <div className="section-header">
                            <h2 className="section-title">今日预约列表</h2>
                            <div className="action-buttons">
                                <div className="search-container">
                                    <input
                                        type="text"
                                        placeholder="搜索客户或服务..."
                                        className="search-input"
                                        onFocus={(e) => e.target.classList.add('search-input-focused')}
                                        onBlur={(e) => e.target.classList.remove('search-input-focused')}
                                    />
                                    <i className="fa fa-search search-icon"></i>
                                </div>
                            </div>
                        </div>

                        <Table
                            columns={appointmentColumns}
                            dataSource={filteredAppointments}
                            rowKey="id"
                            pagination={false}
                            className="custom-ant-table"
                            onRow={(record) => ({
                                onClick: () => handleEditTime(record),
                                style: { cursor: 'pointer' }
                            })}
                        />

                        {/* 预约列表分页控件 */}
                        <div className="pagination-container">
                            <Pagination
                                current={appointmentPage}
                                pageSize={pageSize}
                                total={appointmentTotal}
                                onChange={(page) => setAppointmentPage(page)}
                                showSizeChanger={false}
                                showTotal={(total) => `共 ${total} 条记录`}
                            />
                        </div>
                    </div>

                    {/* 房间卡片 */}
                    <div className="rooms-container card">
                        <div className="section-header">
                            <h2 className="section-title">房间状态</h2>
                        </div>

                        <div className="rooms-grid">
                            {roomData.map(room => {
                                const statusText = statusTextMap[room.status] || '未知';
                                const statusIcon = statusIconMap[room.status] || 'fa-question-circle';
                                const availableSpots = 3 - room.occupiedCount; // 计算空余位置

                                return (
                                    <div
                                        key={room.id}
                                        className={`room-card status-${room.status}`}
                                    >
                                        <div className="room-header">
                                            <h3 className="room-name">
                                                <i className="fa fa-building-o"></i>
                                                {room.name}
                                            </h3>
                                            <span className={`room-status ${room.status}`}>
                                                <i className={`fa ${statusIcon}`}></i>
                                                {statusText}
                                            </span>
                                        </div>

                                        {/* 仅在"未满"状态时显示空余位置 */}
                                        {room.status === 'reserved' && (
                                            <div className="room-available-spots">
                                                空余位置: {availableSpots}
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            </div>

            {/* 修改预约时间弹窗 - 使用TimePicker组件 */}
            <div className={`modal ${showEditModal ? 'show' : ''}`}>
                <div className="modal-overlay" onClick={() => setShowEditModal(false)}></div>
                <div className="modal-content" style={{ minWidth: '320px', padding: '20px 20px 10px' }}>
                    <div className="modal-header">
                        <h3 style={{ fontSize: '1.4rem', margin: '0 0 15px 0' }}>修改预约时间</h3>
                        <button className="modal-close" onClick={() => setShowEditModal(false)}
                            style={{ fontSize: '1.2rem', width: '40px', height: '40px' }}>
                            <i className="fa fa-times"></i>
                        </button>
                    </div>
                    <div className="modal-body">
                        <div className="form-group" style={{ marginBottom: '25px' }}>
                            <label style={{ fontSize: '1.1rem', marginBottom: '10px', display: 'block' }}>
                                选择新的开始时间：
                            </label>
                            {/* 使用Ant Design的TimePicker组件 */}
                            <TimePicker
                                value={newTime}
                                onChange={setNewTime}
                                format="HH:mm"
                                style={{
                                    width: '100%',
                                    fontSize: '16px',
                                    padding: '15px',
                                    height: '60px',
                                    borderRadius: '8px',
                                    border: '2px solid #ddd'
                                }}
                                minuteStep={5} // 步长设置为5分钟，便于快速选择
                                allowClear={false}
                                placeholder="选择时间"
                                showNow={false}
                            />
                            <p className="form-hint" style={{ fontSize: '0.9rem', marginTop: '8px' }}>
                                结束时间将自动计算（保持原有时长）
                            </p>
                        </div>
                    </div>
                    <div className="modal-footer" style={{ display: 'flex', gap: '15px', marginTop: '15px' }}>
                        <button
                            className="btn btn-gray"
                            onClick={() => setShowEditModal(false)}
                            style={{ ...getButtonStyle('gray'), padding: '12px 24px', fontSize: '1.1rem', flex: 1 }}
                        >
                            取消
                        </button>
                        <button
                            className="btn btn-primary"
                            onClick={saveNewTime}
                            style={{ ...getButtonStyle('primary'), padding: '12px 24px', fontSize: '1.1rem', flex: 1 }}
                            disabled={!newTime}
                        >
                            保存
                        </button>
                    </div>
                </div>
            </div>

            {/* 新增客户弹窗 - 优化版 */}
            <div className={`modal ${showAddCustomerModal ? 'show' : ''}`}>
                <div className="modal-overlay" onClick={() => setShowAddCustomerModal(false)}></div>
                <div className="modal-content customer-modal">
                    <div className="modal-header">
                        <h3>新客户登记</h3>
                        <button className="modal-close" onClick={() => setShowAddCustomerModal(false)}>
                            <i className="fa fa-times"></i>
                        </button>
                    </div>
                    <div className="modal-body">
                        <div className="form-group">
                            <label>姓名：</label>
                            <input
                                type="text"
                                value={newCustomer.name}
                                onChange={(e) => setNewCustomer({ ...newCustomer, name: e.target.value })}
                                className="form-control"
                                placeholder="请输入客户姓名"
                            />
                        </div>
                        <div className="form-group">
                            <label>电话：</label>
                            <input
                                type="tel"
                                value={newCustomer.phone}
                                onChange={(e) => setNewCustomer({ ...newCustomer, phone: e.target.value })}
                                className="form-control"
                                placeholder="请输入电话号码"
                            />
                        </div>
                        <div className="form-group gender-selection">
                            <label>性别：</label>
                            <div className="gender-options">
                                <label className="gender-option">
                                    <input
                                        type="radio"
                                        name="gender"
                                        value="male"
                                        checked={newCustomer.gender === 'male'}
                                        onChange={() => setNewCustomer({ ...newCustomer, gender: 'male' })}
                                    />
                                    <span className="gender-icon"><i className="fa fa-male"></i></span>
                                    <span className="gender-text">男</span>
                                </label>
                                <label className="gender-option">
                                    <input
                                        type="radio"
                                        name="gender"
                                        value="female"
                                        checked={newCustomer.gender === 'female'}
                                        onChange={() => setNewCustomer({ ...newCustomer, gender: 'female' })}
                                    />
                                    <span className="gender-icon"><i className="fa fa-female"></i></span>
                                    <span className="gender-text">女</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div className="modal-footer customer-modal-footer">
                        <button
                            className="btn btn-gray customer-btn"
                            onClick={() => setShowAddCustomerModal(false)}
                            style={getButtonStyle('gray')}
                        >
                            取消
                        </button>
                        <button
                            className="btn btn-primary customer-btn"
                            onClick={saveNewCustomer}
                            style={getButtonStyle('primary')}
                            disabled={!newCustomer.name || !newCustomer.phone}
                        >
                            保存
                        </button>
                    </div>
                </div>
            </div>

            {/* 确认操作弹窗 */}
            <div className={`alert-modal ${alertModal.visible ? 'show' : ''}`}>
                <div className="modal-overlay" onClick={closeAlert}></div>
                <div className="alert-modal-content">
                    <div className="alert-modal-header">
                        <h3>{alertModal.title}</h3>
                        <button className="modal-close" onClick={closeAlert}>
                            <i className="fa fa-times"></i>
                        </button>
                    </div>
                    <div className="alert-modal-body">
                        <p dangerouslySetInnerHTML={{ __html: alertModal.content }}></p>
                    </div>
                    <div className="alert-modal-footer">
                        {alertModal.showCancel && (
                            <button
                                className="btn btn-gray alert-btn"
                                onClick={handleCancel}
                                style={getButtonStyle('gray')}
                            >
                                {alertModal.cancelText}
                            </button>
                        )}
                        <button
                            className="btn btn-primary alert-btn"
                            onClick={handleConfirm}
                            style={alertModal.title.includes('取消') ? getButtonStyle('red') : getButtonStyle('primary')}
                        >
                            {alertModal.confirmText}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Main;
